<template>
  <div class="app-container">
    <!-- 标题信息 -->
    <div class="header">
      <span class="big-dark-yellow">
        {{ trainItem.trainNo }} &nbsp;&nbsp; 部件名称：{{ trainItem.partName }}
        <br> 下载时间：{{ trainItem.time }}
      </span>
    </div>

    <!-- 筛选区域 -->
    <div class="filter-container">
      <!-- 列筛选 -->
      <el-select
        v-model="filterColumn"
        placeholder="选择列"
        class="filter-item"
        style="width: 150px;"
      >
        <el-option
          v-for="column in columns"
          :key="column.prop"
          :label="column.label"
          :value="column.prop"
        />
      </el-select>

      <!-- 操作符筛选 -->
      <el-select
        v-model="filterOperation"
        placeholder="操作"
        class="filter-item"
        style="width: 100px;"
      >
        <el-option label=">" value=">" />
        <el-option label="<" value="<" />
        <el-option label="=" value="=" />
      </el-select>

      <!-- 筛选值输入 -->
      <el-input
        v-model="filterValue"
        placeholder="值"
        class="filter-item"
        style="width: 100px;"
        @keyup.enter.native="handleFilter"
      />

      <!-- 搜索按钮 -->
      <el-button
        v-waves
        class="filter-item"
        type="primary"
        icon="el-icon-search"
        @click="handleFilter"
      >
        搜索
      </el-button>

      <!-- 取消筛选按钮 -->
      <el-button
        v-waves
        class="filter-item"
        type="warning"
        icon=""
        @click="cancelFilter"
      >
        取消
      </el-button>

      <!-- 图表按钮 -->
      <el-button
        class="filter-item"
        style="margin-left: 10px;"
        type="primary"
        icon="el-icon-s-data"
        @click="handleCharts"
      >
        图表
      </el-button>

      <!-- 数字量筛选 -->
      <el-select
        v-model="selectedColumns"
        multiple
        collapse-tags
        filterable
        placeholder="数字量"
        class="filter-item"
        style="margin-left: 10px"
      >
        <el-option-group label="数字量">
          <el-option
            v-for="(value, key) in columnDigital"
            :key="key"
            :label="key"
            :value="key"
          />
        </el-option-group>
      </el-select>

      <!-- 模拟量筛选 -->
      <el-select
        v-model="selectedColumns"
        multiple
        collapse-tags
        filterable
        placeholder="模拟量"
        class="filter-item"
        style="margin-left: 10px;"
      >
        <el-option-group label="模拟量">
          <el-option
            v-for="(value, key) in columnAnalog"
            :key="key"
            :label="key"
            :value="key"
          />
        </el-option-group>
      </el-select>

      <!-- 单节按钮 -->
      <el-button
        class="filter-item"
        style="margin-left: 10px;"
        type="primary"
        icon="el-icon-s-data"
        @click="dialogSgVisible = true"
      >
        单节
      </el-button>

      <!-- 审核人复选框（可选） -->
      <!--
      <el-checkbox
        v-model="showReviewer"
        class="filter-item"
        style="margin-left:15px;"
        @change="tableKey = tableKey + 1"
      >
        审核人
      </el-checkbox>
      -->
    </div>

    <!-- 表格展示 -->
    <el-table
      :key="tableKey"
      v-loading="listLoading"
      :data="list"
      border
      fit
      highlight-current-row
      style="width: 100%;"
      @sort-change="sortChange"
      size="mini"
    >
      <el-table-column
        v-for="column in columns"
        v-if="visibleColumns.includes(column.label)"
        :key="column.prop"
        :label="column.label"
        :prop="column.prop"
        :sortable="column.sortable"
        :align="column.align || 'left'"
        :width="column.width || ''"
      >
        <template slot-scope="{ row }">
          <span>{{ row[column.prop] }}</span>
        </template>
      </el-table-column>
    </el-table>

    <!-- 分页组件 -->
    <pagination
      v-show="total > 0"
      :total="total"
      :page.sync="listQuery.page"
      :limit.sync="listQuery.limit"
      @pagination="getTableList"
    />

    <!-- 编辑对话框 -->
    <el-dialog
      :title="textMap[dialogStatus]"
      :visible.sync="dialogFormVisible"
      :modal="false"
      :width="dialogWidth"
    >
      <el-form
        ref="dataForm"
        :rules="rules"
        :model="temp"
        label-position="left"
        label-width="70px"
        style="width: 400px; margin-left:50px;"
      >
        <el-form-item label="类型" prop="type">
          <el-select v-model="temp.type" class="filter-item" placeholder="请选择">
            <el-option
              v-for="item in calendarTypeOptions"
              :key="item.key"
              :label="item.display_name"
              :value="item.key"
            />
          </el-select>
        </el-form-item>
        <el-form-item label="日期" prop="timestamp">
          <el-date-picker v-model="temp.timestamp" type="datetime" placeholder="请选择日期" />
        </el-form-item>
        <el-form-item label="标题" prop="title">
          <el-input v-model="temp.title" />
        </el-form-item>
        <el-form-item label="状态" prop="status">
          <el-select v-model="temp.status" class="filter-item" placeholder="请选择">
            <el-option
              v-for="item in statusOptions"
              :key="item"
              :label="item"
              :value="item"
            />
          </el-select>
        </el-form-item>
        <el-form-item label="重要性">
          <el-rate
            v-model="temp.importance"
            :colors="['#99A9BF', '#F7BA2A', '#FF9900']"
            :max="3"
            style="margin-top:8px;"
          />
        </el-form-item>
        <el-form-item label="备注">
          <el-input
            v-model="temp.remark"
            :autosize="{ minRows: 2, maxRows: 4}"
            type="textarea"
            placeholder="请输入"
          />
        </el-form-item>
      </el-form>
      <div slot="footer" class="dialog-footer">
        <el-button @click="dialogFormVisible = false">取消</el-button>
        <el-button
          type="primary"
          @click="dialogStatus === 'create' ? createData() : updateData()"
        >
          确认
        </el-button>
      </div>
    </el-dialog>

    <!-- 阅读统计对话框 -->
    <el-dialog
      :visible.sync="dialogPvVisible"
      title="阅读统计"
      :modal="false"
      width="50%"
    >
      <el-table :data="pvData" border fit highlight-current-row style="width: 100%">
        <el-table-column prop="key" label="渠道" />
        <el-table-column prop="pv" label="浏览量" />
      </el-table>
      <span slot="footer" class="dialog-footer">
        <el-button type="primary" @click="dialogPvVisible = false">确认</el-button>
      </span>
    </el-dialog>

    <!-- 图表对话框 -->
    <el-dialog
      :visible.sync="dialogChartsVisible"
      :modal="false"
      width="100%"
      custom-class="dialog-custom-height"
    >
      <chartPic
        ref="chartsData"
        @cancleDialogChart="cancleDialog"
      />
    </el-dialog>

    <!-- 单节对话框 -->
    <el-dialog
      :visible.sync="dialogSgVisible"
      width="55%"
    >
      <checkResultSg />
    </el-dialog>
  </div>
</template>

<script>
import chartPic from '@/components/Charts/chartPic'
import checkResultSg from './checkResultSg'
import { fetchListDataAll, fetchListData, fetchList, fetchPv, createArticle, updateArticle } from '@/api/article'
import waves from '@/directive/waves' // waves directive
import { parseTime } from '@/utils'
import Pagination from '@/components/Pagination' // secondary package based on el-pagination

const calendarTypeOptions = [
  { key: 'CN', display_name: '中国' },
  { key: 'US', display_name: '美国' },
  { key: 'JP', display_name: '日本' },
  { key: 'EU', display_name: '欧元区' }
]

// arr to obj, such as { CN : "China", US : "USA" }
const calendarTypeKeyValue = calendarTypeOptions.reduce((acc, cur) => {
  acc[cur.key] = cur.display_name
  return acc
}, {})

export default {
  name: 'CheckResultTable',
  components: { Pagination, chartPic, checkResultSg },
  directives: { waves },
  filters: {
    statusFilter(status) {
      const statusMap = {
        published: 'success',
        draft: 'info',
        deleted: 'danger'
      }
      return statusMap[status]
    },
    typeFilter(type) {
      return calendarTypeKeyValue[type]
    }
  },
  data() {
    return {
      dialogWidth: '80%', // 或者你可以设置一个具体的像素值，例如 '800px'
      filterColumn: '', // 筛选的列名
      filterOperation: '', // 筛选操作（'>'、'<'、'='）
      filterValue: '', // 筛选的值
      tableKey: 0,
      listLoading: false,
      list: [], // 你的数据列
      columns: [
        { label: '序号', prop: 'id', sortable: 'custom', align: 'center', width: '80' },
        { label: '时间', prop: 'date', align: 'center', width: '150px' },
        { label: '大闸运转位', prop: 'bposition', width: '150px' },
        { label: '大闸最小制动', prop: 'bsposition', align: 'center', width: '110px' },
        { label: '大闸制动区', prop: 'bstop', align: 'center', width: '110px' },
        { label: '大闸全制动', prop: 'bstopall', width: '80px' },
        { label: '大闸抑制', prop: 'bcontrol', width: '80px' },
        { label: '大闸重联', prop: 'breconnect', width: '80px' },
        { label: '大闸紧急制动', prop: 'bbrake', width: '80px' },
        { label: '机车实际速度', prop: 'trianspeed', width: '80px' },
        { label: '列车管压力kpa', prop: 'trianpressure', width: '80px' },
        { label: '总风缸压力kpa', prop: 'airpressure', width: '80px' },
        { label: '均衡风缸压力kpa', prop: 'meanspressure', width: '80px' },
        { label: '制动缸压力kpa', prop: 'stoppressure', width: '80px' }
      ],
      dynamicData: {
        xAxisData: ['13:00', '13:05', '13:10', '13:15', '13:20', '13:25', '13:30', '13:35', '13:40', '13:45', '13:50', '13:55', '13:00', '13:05', '13:10', '13:15', '13:20', '13:25', '13:30',
          '13:35', '13:40', '13:45', '13:50', '13:55'],
        seriesData: [
          {
            name: 'CMCC',
            data: [220, 182, 191, 134, 150, 120, 110, 125, 145, 122, 165, 122, 220, 182, 191, 134, 150, 120, 110, 125, 145, 122, 165, 122]
          },
          {
            name: 'CTCC',
            data: [120, 110, 125, 145, 122, 165, 122, 220, 182, 191, 134, 150, 220, 182, 191, 134, 150, 120, 110, 125, 145, 122, 165, 122]
          },
          {
            name: 'CUCC',
            data: [220, 182, 125, 145, 122, 191, 134, 150, 120, 110, 165, 122, 220, 182, 191, 134, 150, 120, 110, 125, 145, 122, 165, 122]
          },
          {
            name: 'da',
            data: [220, 182, 191, 134, 150, 120, 110, 125, 145, 122, 165, 122, 220, 182, 191, 134, 150, 120, 110, 125, 145, 122, 165, 122]
          },
          {
            name: 'dasd',
            data: [120, 110, 125, 145, 122, 165, 122, 220, 182, 191, 134, 150, 220, 182, 191, 134, 150, 120, 110, 125, 145, 122, 165, 122]
          },
          {
            name: 'ada',
            data: [220, 182, 125, 145, 122, 191, 134, 150, 120, 110, 165, 122, 220, 182, 191, 134, 150, 120, 110, 125, 145, 122, 165, 122]
          }
        ]
      },
      columnDigital: {
        序号: true,
        时间: true,
        大闸运转位: true,
        大闸最小制动: true,
        大闸制动区: true,
        大闸全制动: true,
        大闸抑制: true,
        大闸重联: true,
        大闸紧急制动: true
      },
      columnAnalog: {
        机车实际速度: true,
        列车管压力kpa: true,
        总风缸压力kpa: true,
        均衡风缸压力kpa: true,
        制动缸压力kpa: true
      },
      columnMapping: {
        '大闸运转位': 'bposition',
        '大闸最小制动': 'bsposition',
        '大闸制动区': 'bstop',
        '大闸全制动': 'bstopall',
        '大闸抑制': 'bcontrol',
        '大闸重联': 'breconnect',
        '大闸紧急制动': 'bbrake',
        '机车实际速度': 'trianspeed',
        '列车管压力kpa': 'trianpressure',
        '总风缸压力kpa': 'airpressure',
        '均衡风缸压力kpa': 'meanspressure',
        '制动缸压力kpa': 'stoppressure'
      },
      columnSettingsTable: null,
      columnSettings: {
        id: true,
        date: true,
        title: true,
        author: true,
        reviewer: true,
        importance: true,
        readings: true,
        status: true,
        actions: true
      },
      selectedColumns: null,
      selectDigitalColumns: null,
      selectAnalogColumns: null,
      trainItem: {},
      total: 0,
      listQuery: {
        page: 1,
        limit: 20,
        importance: undefined,
        title: undefined,
        type: undefined,
        sort: '+id'
      },
      importanceOptions: [1, 2, 3],
      calendarTypeOptions,
      sortOptions: [{ label: 'ID 升序', key: '+id' }, { label: 'ID 降序', key: '-id' }],
      statusOptions: ['published', 'draft', 'deleted'],
      showReviewer: false,
      temp: {
        id: undefined,
        importance: 1,
        remark: '',
        timestamp: new Date(),
        title: '',
        status: 'published',
        type: ''
      },
      dialogFormVisible: false,
      dialogChartsVisible: false,
      dialogSgVisible: false,
      dialogStatus: '',
      textMap: {
        update: '编辑',
        create: '创建'
      },
      dialogPvVisible: false,
      pvData: [],
      rules: {
        type: [{ required: true, message: '类型是必填项', trigger: 'change' }],
        timestamp: [{ type: 'date', required: true, message: '日期是必填项', trigger: 'change' }],
        title: [{ required: true, message: '标题是必填项', trigger: 'blur' }]
      },
      downloadLoading: false
    }
  },
  computed: {
    visibleColumns() {
      return Object.keys(this.columnSettingsTable).filter(key => this.columnSettingsTable[key] && this.selectedColumns.includes(key))
    }
  },
  watch: {
    selectedColumns(newVal) {
      this.columnSettingsTable = Object.keys(this.columnSettingsTable).reduce((acc, key) => {
        acc[key] = newVal.includes(key)
        return acc
      }, {})
    }
  },
  created() {
    // this.getList()
    this.mergeColumnSettings()
    this.getTableList()
    this.selectedColumns = Object.keys(this.columnSettingsTable).filter(key => this.columnSettingsTable[key])
  },
  methods: {
    cancelFilter() {
      this.getTableList()
      this.selectedColumns = Object.keys(this.columnSettingsTable).filter(key => this.columnSettingsTable[key])
    },
    cancleDialog() {
      this.dialogChartsVisible = false
    },
    trainListData(item) {
      console.log('trainItem', item)
      this.trainItem = item
    },
    getList() {
      this.listLoading = true
      fetchList(this.listQuery).then(response => {
        this.list = response.data.items
        this.total = response.data.total

        // Just to simulate the time of the request
        setTimeout(() => {
          this.listLoading = false
        }, 1.5 * 1000)
      })
    },
    getTableList() {
      this.listLoading = true
      fetchListData(this.listQuery).then(response => {
        this.list = response.data.items
        this.total = response.data.total
        // Just to simulate the time of the request
        setTimeout(() => {
          this.listLoading = false
        }, 1.5 * 1000)
      })
    },
    handleFilter() {
      this.listQuery.page = 1 // 重置页码
      this.listLoading = true
      fetchListDataAll(this.listQuery).then(response => {
        let filteredData = response.data.items
        console.log('filterColumn', this.filterColumn)
        // 根据筛选条件过滤数据
        if (this.filterColumn && this.filterOperation && this.filterValue) {
          filteredData = filteredData.filter(item => {
            const itemValue = item[this.filterColumn]
            const filterValue = parseFloat(this.filterValue)
            switch (this.filterOperation) {
              case '>':
                return itemValue > filterValue
              case '<':
                return itemValue < filterValue
              case '=':
                return itemValue === filterValue
              default:
                return true
            }
          })
        }

        this.list = filteredData
        this.total = filteredData.length
        this.listLoading = false
      })
    },
    mergeColumnSettings() {
      this.columnSettingsTable = {
        ...this.columnAnalog,
        ...this.columnDigital
      }
    },
    handleModifyStatus(row, status) {
      this.$message({
        message: '操作成功',
        type: 'success'
      })
      row.status = status
    },
    sortChange(data) {
      const { prop, order } = data
      if (prop === 'id') {
        this.sortByID(order)
      }
    },
    sortByID(order) {
      if (order === 'ascending') {
        this.listQuery.sort = '+id'
      } else {
        this.listQuery.sort = '-id'
      }
      this.handleFilter()
    },
    resetTemp() {
      this.temp = {
        id: undefined,
        importance: 1,
        remark: '',
        timestamp: new Date(),
        title: '',
        status: 'published',
        type: ''
      }
    },
    handleCharts() {
      this.dialogChartsVisible = true
      const resultdata = {
        xAxisData: [], // x轴数据，这里是日期
        seriesData: [] // 系列数据
      }
      const tabledata = []

      // 获取数据列表
      fetchListDataAll(this.listQuery).then(response => {
        tabledata.push(...response.data.items)
        // 处理数据
        this.processData(tabledata, resultdata, this.columnMapping)
        console.log('resultdata', resultdata)
        // 等待一段时间后，导入数据到图表
        setTimeout(() => {
          this.$refs.chartsData.importData(resultdata)
        }, 1.5 * 1000)
      }).catch(error => {
        console.error('Error fetching data:', error)
      })
    },
    // processData方法用于处理数据
    processData(tabledata, resultdata, columnMapping) {
      // 根据columnSettingsTable设置系列数据
      Object.keys(this.columnSettingsTable).forEach(key => {
        if (this.columnSettingsTable[key] === true && key !== '序号' && key !== '时间') {
          // eslint-disable-next-line no-unused-vars
          const mappedKey = columnMapping[key] // 获取映射后的键名
          resultdata.seriesData.push({
            name: key,
            data: []
          })
        }
      })
      // 遍历tabledata，并为每个条目创建数据点
      tabledata.forEach(item => {
        // 将日期添加到x轴数据
        resultdata.xAxisData.push(item.date)
        // 遍历columnSettingsTable并添加需要的数据
        Object.keys(this.columnSettingsTable).forEach(key => {
          if (this.columnSettingsTable[key] === true && key !== '序号' && key !== '时间') {
            const mappedKey = columnMapping[key] // 获取映射后的键名
            const value = item[mappedKey]// 使用映射后的键名获取值
            // 将数据点添加到系列数据
            this.addDataPointToSeries(resultdata.seriesData, key, value)
          }
        })
      })
    },
    // addDataPointToSeries方法用于将数据点添加到相应的系列
    addDataPointToSeries(seriesData, key, value) {
      const series = seriesData.find(series => series.name === key)
      if (series) {
        series.data.push(value)
      }
    },

    handleCharts_1() {
      this.dialogChartsVisible = true
      // eslint-disable-next-line no-unused-vars
      const resultdata = {
        xAxisData: [], // x轴数据，这里是日期
        seriesData: [] // 系列数据
      }
      // eslint-disable-next-line no-unused-vars
      const tabledata = []
      console.log('visibleColumns', this.visibleColumns)
      fetchListDataAll(this.listQuery).then(response => {
        // eslint-disable-next-line no-const-assign
        tabledata.push(response.data.items)
      })
      console.log('tabledata', tabledata)
      /*
      this.visibleColumns.forEach(name => {
        if (name !== '序号' && name !== '时间') {
          resultdata.seriesData.push({
            name: name,
            data: []
          })
        }
      })
      */
      // eslint-disable-next-line no-undef
      tabledata.forEach(item => {
        const dataPoint = {}

        // 遍历columnSettingsTable并添加需要的数据
        for (const [key, value] of Object.entries(this.columnSettingsTable)) {
          if (value === true && key !== '序号' && key !== '时间') {
            // 这里假设columnSettingsTable的键与TrainData中的键相对应
            // eslint-disable-next-line no-undef
            dataPoint[key] = item[key]
          }
        }

        // 将日期添加到x轴数据
        // eslint-disable-next-line no-undef
        resultdata.xAxisData.push(item.date)
        // 将数据点添加到系列数据
        resultdata.seriesData.push(dataPoint)
        // 将数据点添加到系列数据
      })
      console.log('resultdata', resultdata)
      setTimeout(() => {
        this.$refs.chartsData.importData(this.dynamicData)
      }, 1.5 * 1000)
    },
    handleCreate() {
      this.resetTemp()
      this.dialogStatus = 'create'
      this.dialogFormVisible = true
      this.$nextTick(() => {
        this.$refs['dataForm'].clearValidate()
      })
    },
    createData() {
      this.$refs['dataForm'].validate((valid) => {
        if (valid) {
          this.temp.id = parseInt(Math.random() * 100) + 1024 // mock a id
          this.temp.author = 'vue-element-admin'
          createArticle(this.temp).then(() => {
            this.list.unshift(this.temp)
            this.dialogFormVisible = false
            this.$notify({
              title: '成功',
              message: '创建成功',
              type: 'success',
              duration: 2000
            })
          })
        }
      })
    },
    handleUpdate(row) {
      this.temp = Object.assign({}, row) // copy obj
      this.temp.timestamp = new Date(this.temp.timestamp)
      this.dialogStatus = 'update'
      this.dialogFormVisible = true
      this.$nextTick(() => {
        this.$refs['dataForm'].clearValidate()
      })
    },
    updateData() {
      this.$refs['dataForm'].validate((valid) => {
        if (valid) {
          const tempData = Object.assign({}, this.temp)
          tempData.timestamp = +new Date(tempData.timestamp) // change Thu Nov 30 2017 16:41:05 GMT+0800 (CST) to 1512031311464
          updateArticle(tempData).then(() => {
            const index = this.list.findIndex(v => v.id === this.temp.id)
            this.list.splice(index, 1, this.temp)
            this.dialogFormVisible = false
            this.$notify({
              title: '成功',
              message: '更新成功',
              type: 'success',
              duration: 2000
            })
          })
        }
      })
    },
    handleDelete(row, index) {
      this.$notify({
        title: '成功',
        message: '删除成功',
        type: 'success',
        duration: 2000
      })
      this.list.splice(index, 1)
    },
    handleFetchPv(pv) {
      fetchPv(pv).then(response => {
        this.pvData = response.data.pvData
        this.dialogPvVisible = true
      })
    },
    handleDownload() {
      this.downloadLoading = true
      import('@/vendor/Export2Excel').then(excel => {
        const tHeader = ['timestamp', 'title', 'type', 'importance', 'status']
        const filterVal = ['timestamp', 'title', 'type', 'importance', 'status']
        const data = this.formatJson(filterVal)
        excel.export_json_to_excel({
          header: tHeader,
          data,
          filename: 'table-list'
        })
        this.downloadLoading = false
      })
    },
    formatJson(filterVal) {
      return this.list.map(v => filterVal.map(j => {
        if (j === 'timestamp') {
          return parseTime(v[j])
        } else {
          return v[j]
        }
      }))
    },
    getSortClass: function(key) {
      const sort = this.listQuery.sort
      return sort === `+${key}` ? 'ascending' : 'descending'
    }
  }
}
</script>

<style scoped>
/* 在你的样式表文件中定义这个类 */
.big-dark-yellow {
  font-size: 16px; /* 字体大小增加到原来的1.2倍 */
  color: #FFCC66; /* 暗黄色 */
}

.dialog-custom-height .el-dialog {
  height: 90vh; /* 使用视口高度的90% */
  max-height: 90vh; /* 限制最大高度 */
  overflow: auto; /* 如果内容超出高度，则显示滚动条 */
}

.el-dialog__body {
  padding: 10px 20px;
}

.header {
  margin-bottom: 0px;
}
</style>
